<template>
  <div class="personnel-allocation-container">
    <!-- 页面头部 -->
    <div class="allocation-header">
      <div class="header-content">
        <div class="ancient-title">值班人员分配</div>
        <div class="header-subtitle">阴曹地府 · 人力资源智能调配</div>
      </div>
    </div>

    <!-- 路由信息 -->
    <div class="route-info">
      <a-breadcrumb>
        <a-breadcrumb-item
          ><router-link to="/management"><ApartmentOutlined />机构管理</router-link></a-breadcrumb-item
        >
        <a-breadcrumb-item
          ><router-link to="/management/duty-schedule"><ScheduleOutlined />值班排班系统</router-link></a-breadcrumb-item
        >
        <a-breadcrumb-item><UserOutlined />{{ $route.meta.title }}</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <a-row :gutter="24">
      <!-- 左侧：人员管理 -->
      <a-col :xs="24" :lg="16">
        <a-card title="值班人员管理" :bordered="false">
          <template #extra>
            <a-space>
              <a-button type="primary" @click="showAssignPersonnelModal"> <UserAddOutlined />分配人员 </a-button>
              <a-button @click="autoAllocate"> <ThunderboltOutlined />智能分配 </a-button>
              <a-button @click="exportPersonnel"> <ExportOutlined />导出 </a-button>
            </a-space>
          </template>

          <!-- 筛选区域 -->
          <div class="filter-section">
            <a-row :gutter="16">
              <a-col :span="6">
                <a-select v-model:value="filterDepartment" placeholder="部门筛选" style="width: 100%" allow-clear>
                  <a-select-option value="">全部部门</a-select-option>
                  <a-select-option v-for="dept in allDepartments" :key="dept.id" :value="dept.id">
                    {{ dept.name }}
                  </a-select-option>
                </a-select>
              </a-col>
              <a-col :span="6">
                <a-select v-model:value="filterStatus" placeholder="状态筛选" style="width: 100%" allow-clear>
                  <a-select-option value="">全部状态</a-select-option>
                  <a-select-option value="available">可值班</a-select-option>
                  <a-select-option value="on-duty">值班中</a-select-option>
                  <a-select-option value="rest">休息中</a-select-option>
                  <a-select-option value="leave">请假</a-select-option>
                </a-select>
              </a-col>
              <a-col :span="6">
                <a-select v-model:value="filterPosition" placeholder="职位筛选" style="width: 100%" allow-clear>
                  <a-select-option value="">全部职位</a-select-option>
                  <a-select-option value="王">王</a-select-option>
                  <a-select-option value="判官">判官</a-select-option>
                  <a-select-option value="书记官">书记官</a-select-option>
                  <a-select-option value="执法官">执法官</a-select-option>
                </a-select>
              </a-col>
              <a-col :span="6">
                <a-input-search v-model:value="searchText" placeholder="搜索人员" @search="handleSearch" />
              </a-col>
            </a-row>
          </div>

          <!-- 人员列表 -->
          <div class="personnel-list">
            <div v-for="person in filteredPersonnel" :key="person.id" class="personnel-item">
              <div class="person-header">
                <div class="person-info">
                  <a-avatar :src="person.avatar" size="large">
                    {{ person.name.charAt(0) }}
                  </a-avatar>
                  <div class="person-details">
                    <h4 class="person-name">{{ person.name }}</h4>
                    <p class="person-title">{{ person.department }} - {{ person.position }}</p>
                    <div class="person-tags">
                      <a-tag :color="getStatusColor(person.status)">{{ getStatusText(person.status) }}</a-tag>
                      <a-tag color="blue">等级{{ person.level }}</a-tag>
                      <a-tag color="purple">经验{{ person.experience }}年</a-tag>
                    </div>
                  </div>
                </div>
                <div class="person-actions">
                  <a-dropdown>
                    <a-button type="text"><MoreOutlined /></a-button>
                    <template #overlay>
                      <a-menu>
                        <a-menu-item @click="viewPersonDetail(person)"> <EyeOutlined />查看详情 </a-menu-item>
                        <a-menu-item @click="assignDuty(person)" v-if="person.status === 'available'"> <CalendarOutlined />安排值班 </a-menu-item>
                        <a-menu-item @click="adjustWorkload(person)"> <BarChartOutlined />调整负载 </a-menu-item>
                        <a-menu-divider />
                        <a-menu-item @click="grantLeave(person)" v-if="person.status !== 'leave'"> <LogoutOutlined />批准请假 </a-menu-item>
                      </a-menu>
                    </template>
                  </a-dropdown>
                </div>
              </div>

              <div class="person-workload">
                <div class="workload-info">
                  <span class="workload-label">工作负载</span>
                  <span class="workload-percentage">{{ person.workload }}%</span>
                </div>
                <a-progress :percent="person.workload" size="small" :show-info="false" :stroke-color="getWorkloadColor(person.workload)" />
              </div>

              <div class="person-schedule">
                <h5>本周值班安排</h5>
                <div class="schedule-items">
                  <div v-for="schedule in person.weeklySchedule" :key="schedule.id" class="schedule-item">
                    <span class="schedule-time">{{ schedule.date }} {{ schedule.time }}</span>
                    <span class="schedule-type">{{ schedule.type }}</span>
                    <a-tag :color="schedule.priority === 'high' ? 'red' : 'blue'" size="small">
                      {{ schedule.priority === 'high' ? '重要' : '一般' }}
                    </a-tag>
                  </div>
                  <div v-if="person.weeklySchedule.length === 0" class="no-schedule">暂无值班安排</div>
                </div>
              </div>

              <div class="person-stats">
                <a-row :gutter="16">
                  <a-col :span="6">
                    <div class="stat-item">
                      <div class="stat-number">{{ person.monthlyHours }}</div>
                      <div class="stat-label">本月工时</div>
                    </div>
                  </a-col>
                  <a-col :span="6">
                    <div class="stat-item">
                      <div class="stat-number">{{ person.attendanceRate }}%</div>
                      <div class="stat-label">出勤率</div>
                    </div>
                  </a-col>
                  <a-col :span="6">
                    <div class="stat-item">
                      <div class="stat-number">{{ person.performanceScore }}</div>
                      <div class="stat-label">绩效分</div>
                    </div>
                  </a-col>
                  <a-col :span="6">
                    <div class="stat-item">
                      <div class="stat-number">{{ person.overtimeCount }}</div>
                      <div class="stat-label">加班次数</div>
                    </div>
                  </a-col>
                </a-row>
              </div>
            </div>
          </div>
        </a-card>
      </a-col>

      <!-- 右侧：分配工具和统计 -->
      <a-col :xs="24" :lg="8">
        <a-space direction="vertical" size="large" style="width: 100%">
          <!-- 负载统计 -->
          <a-card title="部门负载统计" size="small" :bordered="false">
            <div class="department-workload">
              <div v-for="dept in departmentStats" :key="dept.id" class="dept-workload-item">
                <div class="dept-info">
                  <span class="dept-name">{{ dept.name }}</span>
                  <span class="dept-load">{{ dept.averageLoad }}%</span>
                </div>
                <div class="load-bar">
                  <div class="load-progress" :class="getLoadLevel(dept.averageLoad)" :style="{ width: dept.averageLoad + '%' }"></div>
                </div>
                <div class="dept-personnel">{{ dept.activePersonnel }}/{{ dept.totalPersonnel }}人在岗</div>
              </div>
            </div>
          </a-card>

          <!-- 值班能力分析 -->
          <a-card title="值班能力分析" size="small" :bordered="false">
            <div class="capability-analysis">
              <div class="capability-item">
                <span class="capability-label">高级仙官：</span>
                <span class="capability-value">{{ capabilityStats.senior }}人</span>
              </div>
              <div class="capability-item">
                <span class="capability-label">中级仙官：</span>
                <span class="capability-value">{{ capabilityStats.intermediate }}人</span>
              </div>
              <div class="capability-item">
                <span class="capability-label">初级仙官：</span>
                <span class="capability-value">{{ capabilityStats.junior }}人</span>
              </div>
              <div class="capability-item">
                <span class="capability-label">可用率：</span>
                <span class="capability-value">{{ capabilityStats.availabilityRate }}%</span>
              </div>
            </div>
          </a-card>

          <!-- 分配建议 -->
          <a-card title="智能分配建议" size="small" :bordered="false">
            <div class="allocation-suggestions">
              <div v-for="suggestion in allocationSuggestions" :key="suggestion.id" class="suggestion-item">
                <div class="suggestion-content">
                  <div class="suggestion-title">{{ suggestion.title }}</div>
                  <div class="suggestion-desc">{{ suggestion.description }}</div>
                </div>
                <div class="suggestion-action">
                  <a-button type="link" size="small" @click="applySuggestion(suggestion)"> 采纳 </a-button>
                </div>
              </div>
            </div>
          </a-card>

          <!-- 快速操作 -->
          <a-card title="快速操作" size="small" :bordered="false">
            <div class="quick-actions">
              <a-button block @click="balanceWorkload" style="margin-bottom: 8px"> <SwapOutlined />负载均衡 </a-button>
              <a-button block @click="emergencyAllocation" style="margin-bottom: 8px"> <AlertOutlined />紧急调配 </a-button>
              <a-button block @click="scheduleOptimization"> <ThunderboltOutlined />排班优化 </a-button>
            </div>
          </a-card>
        </a-space>
      </a-col>
    </a-row>

    <!-- 分配人员弹窗 -->
    <a-modal v-model:open="assignPersonnelModalVisible" title="分配值班人员" @ok="handleAssignPersonnel" width="600px">
      <a-form ref="assignFormRef" :model="assignForm" :rules="assignRules" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="选择人员" name="personnelId">
              <a-select v-model:value="assignForm.personnelId" placeholder="选择人员">
                <a-select-option v-for="person in availablePersonnel" :key="person.id" :value="person.id"> {{ person.name }} - {{ person.position }} </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="值班日期" name="date">
              <a-date-picker v-model:value="assignForm.date" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="开始时间" name="startTime">
              <a-time-picker v-model:value="assignForm.startTime" format="HH:mm" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="结束时间" name="endTime">
              <a-time-picker v-model:value="assignForm.endTime" format="HH:mm" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="值班类型" name="dutyType">
          <a-radio-group v-model:value="assignForm.dutyType">
            <a-radio value="regular">常规值班</a-radio>
            <a-radio value="overtime">加班</a-radio>
            <a-radio value="emergency">紧急值班</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="优先级" name="priority">
          <a-select v-model:value="assignForm.priority" placeholder="选择优先级">
            <a-select-option value="low">低</a-select-option>
            <a-select-option value="medium">中</a-select-option>
            <a-select-option value="high">高</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="备注" name="note">
          <a-textarea v-model:value="assignForm.note" placeholder="值班安排说明" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  HomeOutlined,
  ApartmentOutlined,
  ScheduleOutlined,
  UserOutlined,
  UserAddOutlined,
  ThunderboltOutlined,
  ExportOutlined,
  MoreOutlined,
  EyeOutlined,
  CalendarOutlined,
  BarChartOutlined,
  LogoutOutlined,
  SwapOutlined,
  AlertOutlined
} from '@ant-design/icons-vue'

// 响应式数据
const searchText = ref('')
const filterDepartment = ref('')
const filterStatus = ref('')
const filterPosition = ref('')
const assignPersonnelModalVisible = ref(false)
const assignFormRef = ref()

// 部门数据
const allDepartments = ref([
  { id: 1, name: '第一殿秦广王府' },
  { id: 2, name: '第二殿楚江王府' },
  { id: 5, name: '第五殿阎罗王府' },
  { id: 10, name: '第十殿转轮王府' }
])

// 人员数据
const personnel = ref([
  {
    id: 1,
    name: '秦广王',
    department: '第一殿秦广王府',
    position: '王',
    level: 9,
    experience: 500,
    status: 'on-duty',
    workload: 85,
    monthlyHours: 180,
    attendanceRate: 98,
    performanceScore: 95,
    overtimeCount: 3,
    avatar: '',
    weeklySchedule: [
      { id: 1, date: '周一', time: '08:00-18:00', type: '常规值班', priority: 'high' },
      { id: 2, date: '周三', time: '18:00-06:00', type: '夜班', priority: 'medium' }
    ]
  },
  {
    id: 2,
    name: '判官李明',
    department: '第一殿秦广王府',
    position: '判官',
    level: 7,
    experience: 200,
    status: 'available',
    workload: 65,
    monthlyHours: 150,
    attendanceRate: 96,
    performanceScore: 88,
    overtimeCount: 1,
    avatar: '',
    weeklySchedule: [{ id: 3, date: '周二', time: '08:00-18:00', type: '常规值班', priority: 'medium' }]
  },
  {
    id: 3,
    name: '阎罗王',
    department: '第五殿阎罗王府',
    position: '王',
    level: 10,
    experience: 1000,
    status: 'on-duty',
    workload: 92,
    monthlyHours: 200,
    attendanceRate: 99,
    performanceScore: 98,
    overtimeCount: 5,
    avatar: '',
    weeklySchedule: [
      { id: 4, date: '周一', time: '00:00-24:00', type: '全天值班', priority: 'high' },
      { id: 5, date: '周五', time: '18:00-06:00', type: '夜班', priority: 'high' }
    ]
  },
  {
    id: 4,
    name: '黑白无常',
    department: '第五殿阎罗王府',
    position: '执法官',
    level: 8,
    experience: 300,
    status: 'rest',
    workload: 45,
    monthlyHours: 120,
    attendanceRate: 94,
    performanceScore: 90,
    overtimeCount: 2,
    avatar: '',
    weeklySchedule: []
  }
])

// 部门统计
const departmentStats = ref([
  { id: 1, name: '第一殿', averageLoad: 75, activePersonnel: 8, totalPersonnel: 12 },
  { id: 2, name: '第二殿', averageLoad: 68, activePersonnel: 6, totalPersonnel: 10 },
  { id: 5, name: '第五殿', averageLoad: 88, activePersonnel: 15, totalPersonnel: 18 },
  { id: 10, name: '第十殿', averageLoad: 82, activePersonnel: 12, totalPersonnel: 15 }
])

// 能力统计
const capabilityStats = reactive({
  senior: 25,
  intermediate: 45,
  junior: 30,
  availabilityRate: 78
})

// 分配建议
const allocationSuggestions = ref([
  {
    id: 1,
    title: '第二殿人员不足',
    description: '建议从第一殿调配2名判官支援'
  },
  {
    id: 2,
    title: '夜班人员紧张',
    description: '建议增加夜班津贴，提高夜班值班积极性'
  },
  {
    id: 3,
    title: '工作负载不均',
    description: '第五殿负载过重，建议重新分配任务'
  }
])

// 表单数据
const assignForm = reactive({
  personnelId: null,
  date: null,
  startTime: null,
  endTime: null,
  dutyType: 'regular',
  priority: 'medium',
  note: ''
})

// 表单验证规则
const assignRules = {
  personnelId: [{ required: true, message: '请选择人员', trigger: 'change' }],
  date: [{ required: true, message: '请选择值班日期', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
}

// 计算属性
const filteredPersonnel = computed(() => {
  let result = personnel.value

  if (filterDepartment.value) {
    result = result.filter((person) => person.department.includes(getDepartmentName(filterDepartment.value)))
  }

  if (filterStatus.value) {
    result = result.filter((person) => person.status === filterStatus.value)
  }

  if (filterPosition.value) {
    result = result.filter((person) => person.position === filterPosition.value)
  }

  if (searchText.value) {
    result = result.filter((person) => person.name.toLowerCase().includes(searchText.value.toLowerCase()))
  }

  return result
})

const availablePersonnel = computed(() => {
  return personnel.value.filter((person) => person.status === 'available')
})

// 方法
const getDepartmentName = (deptId) => {
  const dept = allDepartments.value.find((d) => d.id === deptId)
  return dept ? dept.name : ''
}

const getStatusColor = (status) => {
  const colors = {
    available: 'green',
    'on-duty': 'blue',
    rest: 'orange',
    leave: 'red'
  }
  return colors[status] || 'default'
}

const getStatusText = (status) => {
  const texts = {
    available: '可值班',
    'on-duty': '值班中',
    rest: '休息中',
    leave: '请假'
  }
  return texts[status] || status
}

const getWorkloadColor = (workload) => {
  if (workload >= 90) return '#ff4d4f'
  if (workload >= 70) return '#fa8c16'
  return '#52c41a'
}

const getLoadLevel = (load) => {
  if (load >= 90) return 'high-load'
  if (load >= 70) return 'medium-load'
  return 'low-load'
}

const showAssignPersonnelModal = () => {
  Object.assign(assignForm, {
    personnelId: null,
    date: null,
    startTime: null,
    endTime: null,
    dutyType: 'regular',
    priority: 'medium',
    note: ''
  })
  assignPersonnelModalVisible.value = true
}

const handleAssignPersonnel = async () => {
  try {
    await assignFormRef.value.validate()
    message.success('人员分配成功')
    assignPersonnelModalVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const viewPersonDetail = (person) => {
  message.info(`查看 ${person.name} 详细信息`)
}

const assignDuty = (person) => {
  message.info(`为 ${person.name} 安排值班`)
}

const adjustWorkload = (person) => {
  message.info(`调整 ${person.name} 工作负载`)
}

const grantLeave = (person) => {
  message.info(`批准 ${person.name} 请假`)
}

const autoAllocate = () => {
  message.info('启动智能分配算法...')
}

const applySuggestion = (suggestion) => {
  message.success(`已采纳建议: ${suggestion.title}`)
}

const balanceWorkload = () => {
  message.info('负载均衡功能启动...')
}

const emergencyAllocation = () => {
  message.info('紧急调配程序启动...')
}

const scheduleOptimization = () => {
  message.info('排班优化程序启动...')
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const exportPersonnel = () => {
  message.info('人员数据导出功能开发中...')
}

onMounted(() => {
  // 页面加载时的初始化逻辑
})
</script>

<style lang="scss" scoped>
.personnel-allocation-container {
  padding: 24px;

  .allocation-header {
    text-align: center;
    margin-bottom: 32px;

    .header-content {
      .ancient-title {
        font-size: 32px;
        font-weight: bold;
        color: $secondary-color;
        margin-bottom: 8px;
        text-shadow: 0 0 20px rgba(212, 153, 10, 0.3);
      }

      .header-subtitle {
        font-size: 16px;
        color: $text-secondary;
        letter-spacing: 2px;
      }
    }
  }

  .route-info {
    margin-bottom: 24px;
    padding: 12px 16px;
    border-radius: 8px;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(212, 153, 10, 0.2);
  }

  .filter-section {
    margin-bottom: 20px;
    padding: 16px;
    border-radius: 8px;
    border: 1px solid rgba(212, 153, 10, 0.2);
  }

  .personnel-list {
    .personnel-item {
      margin-bottom: 20px;
      padding: 24px;
      border: 1px solid rgba(212, 153, 10, 0.2);
      border-radius: 12px;
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
      }

      .person-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 16px;

        .person-info {
          display: flex;
          gap: 16px;
          flex: 1;

          .person-details {
            .person-name {
              margin: 0 0 4px 0;
              color: $primary-color;
              font-size: 18px;
              font-weight: bold;
            }

            .person-title {
              margin: 0 0 8px 0;
              color: $text-secondary;
              font-size: 14px;
            }

            .person-tags {
              .ant-tag {
                margin-right: 8px;
              }
            }
          }
        }
      }

      .person-workload {
        margin-bottom: 16px;

        .workload-info {
          display: flex;
          justify-content: space-between;
          margin-bottom: 8px;

          .workload-label {
            color: $text-secondary;
            font-size: 14px;
          }

          .workload-percentage {
            color: $secondary-color;
            font-weight: bold;
            font-size: 14px;
          }
        }
      }

      .person-schedule {
        margin-bottom: 16px;

        h5 {
          margin: 0 0 12px 0;
          color: $primary-color;
          font-size: 14px;
          font-weight: bold;
        }

        .schedule-items {
          .schedule-item {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 8px;
            padding: 8px;
            background: rgba(212, 153, 10, 0.05);
            border-radius: 4px;

            .schedule-time {
              font-size: 14px;
              color: $text-primary;
              font-weight: 500;
            }

            .schedule-type {
              font-size: 13px;
              color: $text-secondary;
            }
          }

          .no-schedule {
            color: $text-secondary;
            font-style: italic;
            padding: 8px;
          }
        }
      }

      .person-stats {
        .stat-item {
          text-align: center;

          .stat-number {
            font-size: 18px;
            font-weight: bold;
            color: $secondary-color;
            margin-bottom: 4px;
          }

          .stat-label {
            font-size: 12px;
            color: $text-secondary;
          }
        }
      }
    }
  }

  .department-workload {
    .dept-workload-item {
      margin-bottom: 16px;

      .dept-info {
        display: flex;
        justify-content: space-between;
        margin-bottom: 4px;
        font-size: 14px;

        .dept-name {
          color: $text-primary;
        }

        .dept-load {
          color: $secondary-color;
          font-weight: bold;
        }
      }

      .load-bar {
        height: 8px;
        background: #f0f0f0;
        border-radius: 4px;
        overflow: hidden;
        margin-bottom: 4px;

        .load-progress {
          height: 100%;
          transition: width 0.3s ease;

          &.low-load {
            background: #52c41a;
          }
          &.medium-load {
            background: #fa8c16;
          }
          &.high-load {
            background: #ff4d4f;
          }
        }
      }

      .dept-personnel {
        font-size: 12px;
        color: $text-secondary;
      }
    }
  }

  .capability-analysis {
    .capability-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;

      .capability-label {
        color: $text-secondary;
        font-size: 14px;
      }

      .capability-value {
        color: $secondary-color;
        font-weight: bold;
        font-size: 14px;
      }
    }
  }

  .allocation-suggestions {
    .suggestion-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid rgba(212, 153, 10, 0.1);

      &:last-child {
        border-bottom: none;
      }

      .suggestion-content {
        flex: 1;

        .suggestion-title {
          font-size: 14px;
          font-weight: bold;
          color: $primary-color;
          margin-bottom: 4px;
        }

        .suggestion-desc {
          font-size: 12px;
          color: $text-secondary;
        }
      }
    }
  }

  .quick-actions {
    .ant-btn {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      gap: 8px;
    }
  }

  :deep(.ant-card) {
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    border: 1px solid rgba(212, 153, 10, 0.2);
    border-radius: 12px;
  }

  :deep(.ant-card-head) {
    border-bottom: 1px solid rgba(212, 153, 10, 0.2);
  }
}
</style>
